package com.example.aliyuntest.ui;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.example.aliyuntest.data.Task;
import com.example.aliyuntest.databinding.ItemTaskBinding;

import java.util.List;

public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder> {

    private List<Task> items;
    private final OnTaskClickListener listener;
    private OnTaskLongClickListener longClickListener;

    public interface OnTaskClickListener {
        void onTaskClick(Task task);
    }
    public interface OnTaskLongClickListener {
        void onTaskLongClick(Task task);
    }

    public TaskAdapter(List<Task> items, OnTaskClickListener listener) {
        this.items = items;
        this.listener = listener;
    }
    public void setOnTaskLongClickListener(OnTaskLongClickListener longClickListener) {
        this.longClickListener = longClickListener;
    }
    static class TaskViewHolder extends RecyclerView.ViewHolder {
        private final CheckBox checkbox;

        public TaskViewHolder(ItemTaskBinding binding) {
            super(binding.getRoot());
            checkbox = binding.checkbox;
        }

        public void bind(Task task, OnTaskClickListener listener, OnTaskLongClickListener longClickListener) {
            checkbox.setText(task.getName());
            checkbox.setChecked(task.isDone());
            checkbox.setOnClickListener(v -> listener.onTaskClick(task));

            itemView.setOnLongClickListener(v -> {
                if (longClickListener != null) {
                    longClickListener.onTaskLongClick(task);
                    return true; // 表示事件已消费
                }
                return false;
            });
        }
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemTaskBinding binding = ItemTaskBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new TaskViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        holder.bind(items.get(position), listener, longClickListener);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public void submitList(List<Task> newItems) {
        this.items = newItems;
        notifyDataSetChanged();
    }
}